namespace MonitorTemperatura.DataAccess
{
    using Db4objects.Db4o;
    using Db4objects.Db4o.Messaging;
    using System;
    using System.Diagnostics;
    using System.Threading;

    public class StartServer : Util, IMessageRecipient
    {
        private bool stop = false;

        public void Close()
        {
            lock (this)
            {
                this.stop = true;
                Monitor.PulseAll(this);
            }
        }

        public static void Start(string[] arguments)
        {
            new StartServer().RunServer();
        }

        public void ProcessMessage(IMessageContext con, object message)
        {
            if (message is StopServer)
            {
                this.Close();
            }
        }

        public void RunServer()
        {
            lock (this)
            {
                try
                {
                    IObjectServer server = Db4oFactory.OpenServer(YapFileName, PORT);
                    server.GrantAccess(USER, PASS);
                    server.Ext().Configure().ClientServer().SetMessageRecipient(this);
                    try
                    {
                        if (!this.stop)
                        {
                            Monitor.Wait(this);
                        }
                    }
                    catch (Exception exception)
                    {
                        System.Diagnostics.EventLog.WriteEntry("MonitorTemperatura", exception.ToString());
                    }
                    server.Close();
                }
                catch (Exception ex)
                {
                    System.Diagnostics.EventLog.WriteEntry("MonitorTemperatura", ex.ToString());                    
                }
            }
        }
    }
}

